import './add.less';
import Panel from "../../elements/Panel";
import Header from "../../components/Header";
import Modal from "../../components/Modal/";
import {connect} from "react-redux";
import {Config, Lang, Fetch_} from "../../libs/";
import {URL, md5Url} from "../../libs/Url";
import Label from "../../components/FormLabel";
import FormGroup from "../../components/FormGroup";
import FormItem from "../../components/FormItem";
import FormItemType from "../../components/FormItemType";
import InputGroup from "../../components/InputGroup";
import Selected from "../../components/SelectItem";
import BreadcrumbNavigation from "../../components/BreadcrumbNavigation";
import {fetch, fetchUser} from "../../actions";
import {t} from "../../libs/schedule";
import {SUBJECT, PAGE_SUBJECT} from "../../actions/subject";
import Canlendar from '../../components/canlendar/'

const Component = React.createClass({
    getInitialState(){

        const self = this;
        this.isUpdate = this.props.router.params.id;
        return {
            open: false,
            list: {}, // 课程表
            result: {}, //选中变量
            tmp: {},//选中课程缓存变量
            selected: '',
            selected_: {},//選中課程
            active_class: '',
            num: 0,
            today: Moment(new Date()).format('YYYY年MM月DD日'),
            form: [
                {
                    name: 'subject',
                    label: '科目',
                    placeholder: '',
                    value: '',
                    type: FormItemType.TEXT_SHOW,
                },
                {
                    name: 'teacher',
                    label: '教师',
                    placeholder: '',
                    value: '',
                    type: FormItemType.TEXT_SHOW,
                },
                {
                    name: 'comment',
                    label: '详情',
                    placeholder: '',
                    required: true,
                    value: '',
                    type: FormItemType.TEXT_AREA,
                    onchange: function (index, content) {
                        self.setState({
                            form: [
                                ...self.state.form.slice(0, index),
                                Object.assign({}, self.state.form[index], {
                                    value: content,
                                    tips: content.length ? '' : '该项必填',
                                }),
                                ...self.state.form.slice(index + 1),
                            ]
                        });
                    }
                },
                {
                    name: 'fileids',
                    label: '附件',
                    value: '',
                    placeholder: '',
                    tips: '',
                    type: FormItemType.UPLOAD,
                    onchange: function (index, content) {
                        self.setState({
                            form: [
                                ...self.state.form.slice(0, index),
                                Object.assign({}, self.state.form[index], {
                                    value: content,
                                    tips: content.length ? '' : '该项必填',
                                }),
                                ...self.state.form.slice(index + 1),
                            ]
                        });
                    }
                },
                {
                    name: 'classid',
                    label: '推送设置',
                    value: '',
                    tips: '',
                    required: true,
                    type: FormItemType.MODAL_CHECK_BOX,
                    onchange: function (index, content) {
                        self.setState({
                            form: [
                                ...self.state.form.slice(0, index),
                                Object.assign({}, self.state.form[index], {
                                    value: content,
                                    tips: content.length ? '' : '该项必填',
                                }),
                                ...self.state.form.slice(index + 1),
                            ]
                        });
                    }
                },
            ],

            tips: {}
        }
    },
    setchange(index, content){
        const self = this;
        self.setState({
            form: [
                ...self.state.form.slice(0, index),
                Object.assign({}, self.state.form[index], {
                    value: content,
                    tips: content.length ? '' : '该项必填',
                }),
                ...self.state.form.slice(index + 1),
            ]
        })
    },
    componentDidMount() {
        const {dispatch, user} = this.props, self = this;

        if (user['class'] instanceof Array) {
            Fetch_(URL.Get_USER_CLASS)
                .then(resC=> {
                    var schedules = [];

                    resC.list.forEach(item=> {
                        schedules.push(Fetch_(URL.SCHEDULE_GET, {body: {classid: item.classid}}))
                    });
                    if (self.props.router.params.id) {
                        schedules.push(Fetch_(URL.HOMEWORK_GET, {body: {homeworkid: self.props.router.params.id}}));
                    }
                    Promise.all(schedules)
                        .then(res=> {
                            var schedule = {};
                            var last = res[res.length - 1].homework;
                            // var frist = res[0];
                            res.slice(0, resC.list.length).forEach((item, index)=> {
                                console.log(item);
                                schedule[resC.list[index].classid] = Object.assign({}, {
                                    list: item.list,
                                    classInfo: resC.list[index]
                                }, self.props.router.params.id && resC.list[index].classid == last['class'].classid ? {
                                    selected: {[last.time.trim()]: true},
                                    tmp: {},
                                } : {
                                    selected: {},
                                    tmp: {},
                                });
                            });

                            console.log(last)
                            self.setState(Object.assign({}, {
                                schedules: schedule,
                            }, self.props.router.params.id ? {
                                form: [
                                    ...self.state.form.slice(0, 2),
                                    Object.assign({}, self.state.form[2], {comment: last.comment}),
                                    Object.assign({}, self.state.form[3], {comment: last.fileids}),
                                    ...self.state.form.slice(4),
                                ],
                                homework: last,
                            } : {}));
                        })
                        .catch(e=> {
                            console.log(e);
                        })
                })

        }

        dispatch(fetch({url: URL.SCHEDULE_GET, classid: ''}));

        dispatch(fetchUser()); //获取登录用户信息
    },
    onsubmit(){
        const {dispatch} = this.props;
        const self = this;

        var can_submit = true, form = {};
        self.state.form.forEach((item, index)=> {
            if (!this.isUpdate && item.required && item.value.length == 0) {
                self.setState({
                    form: [
                        ...self.state.form.slice(0, index),
                        Object.assign({}, self.state.form[index], {
                            tips: '该项必填',
                        }),
                        ...self.state.form.slice(index + 1),
                    ]
                });
                can_submit = false;
            } else {
                form[item.name] = item.value
            }
        });
        if (can_submit) {
            form.classid = form.classid.slice(1);
            form.classList = [];
            if (this.state.schedules && Object.keys(this.state.schedules).length > 0) {
                Object.keys(this.state.schedules).forEach(item=> {
                    var item_ = this.state.schedules[item];
                    if (item_.selected && (item_.selected instanceof Object) && Object.keys(item_.selected).length) {
                        form.classList.push({
                            teachid: item_.classInfo.teachid,
                            time: Object.keys(item_.selected).toString()
                        })
                    }
                })
            }
            if (this.isUpdate) {
                form.homeworkid = this.isUpdate;
            }
            if (form.classid) {
                delete  form.classid;
            }
            form.url = URL.NEWS_ADD;
            Fetch_(this.isUpdate ? URL.HOMEWORK_MODIFY : URL.HOMEWORK_ADD, {body: form, method: 'POST'})
                .then(data=> {
                    alert('成功!');
                    if (!self.isUpdate) {
                        self.props.router.push(Config.MENUS_ABSOLUTE.HOMEWORK)
                    }
                })
                .catch(e=> {
                    console.log(e);
                    alert('失败!')
                });
            // dispatch(fetch(SUBJECT.NEWS_ADD, form))
        }
    },
    componentWillReceiveProps(nextProps){
        var self = this;
        if (nextProps['user']) {
            let schedules = [];
            // nextProps['user'].class.map(item=> {
            //     if (item.class && item.class.id) {
            //         (!self.state[item.class.id] ) && Fetch_(URL.SCHEDULE_GET, {body: {classid: item.class.id}})
            //             .then(res=> {
            //                 let body = t(res.list.subjects, res.list.timetable, res.list.classtime, false);
            //                 self.setState({
            //                     list: Object.assign({}, ...self.state.list, {[item.class.id]: body})
            //                 });
            //             })
            //             .catch(e=> {
            //                 console.log(e)
            //             });
            //     } else {
            //         (!self.state[item.id] ) && Fetch_(URL.SCHEDULE_GET, {body: {classid: item.id}})
            //             .then(res=> {
            //                 let body = t(res.list.subjects, res.list.timetable, res.list.classtime, false);
            //
            //                 self.setState({
            //                     list: Object.assign({}, ...self.state.list, {[item.id]: body})
            //                 });
            //             })
            //             .catch(e=> {
            //                 console.log(e)
            //             });
            //     }
            // });
        }
    },

    render(){
        const self = this;
        const {user, dispatch}  = this.props, state = this.state;
        var form = self.state.form;
        if (state.homework) {
            form[2].value = form[2].value || state.homework['comment'];
            form[3].value = form[3].value || state.homework['fileids'];
            // form[4].value =state.homework['fileids'];
            // if(Object.keys(state.schedules).length > 0){
            //
            // }
        }

        return (
            <div>
                <BreadcrumbNavigation navs={[
                    {url: Config.MENUS_ABSOLUTE.HOME, label: Lang.menus.HOME},
                    {url: Config.MENUS_ABSOLUTE.HOMEWORK, label: Lang.menus.HOMEWORK},
                    {label: this.isUpdate ? Lang.menus.HOMEWORK_UPDATE : Lang.menus.HOMEWORK_CRATE},
                ]}></BreadcrumbNavigation>
                <Panel>
                    <Header>{this.isUpdate ? Lang.menus.HOMEWORK_UPDATE : Lang.menus.HOMEWORK_CRATE}</Header>
                    <div className="form-horizontal">
                        {
                            form.map((item, index)=> {
                                if (index == 0) {
                                    item.value = (user['class'] && user['class'].length) ?
                                        (user['class'][0]['subject'] && user['class'][0]['subject'].name) : '';
                                }
                                if (index == 1) {
                                    item.value = user.name;
                                }
                                if (item.type == FormItemType.MODAL_CHECK_BOX) {
                                    return <FormItem {...item} key={index}>
                                        <div className="homeword">
                                            <ul className="homeword-set">
                                                {
                                                    user.class.map((item_, idex)=> {
                                                        item_.checked = self.state.form[index].value.indexOf(item_.id) > -1;
                                                        var id = ((item_.class && item_.class.id) || item_.id);

                                                        var date_ = '';

                                                        if (self.state.schedules &&
                                                            self.state.schedules[item_.classid] && !_.isEmpty(self.state.schedules[item_.classid]) &&
                                                            self.state.schedules[item_.classid].selected) {

                                                            date_ = Object.keys(self.state.schedules[item_.classid]
                                                                .selected).toString();
                                                        }
                                                        return <li key={idex}>
                                                            <b>{item_.name || item_.class.name}</b>
                                                            <span
                                                                className="text-success">{date_ || '未设置'}</span>
                                                            <span className="pull-right">
                                                                <button
                                                                    className="btn btn-default btn-xs"
                                                                    onClick={()=> {
                                                                        if (self.state.schedules[item_.classid]) {
                                                                            if (self.state.schedules[item_.classid].list.timetable.length == 0) {
                                                                                return alert('该班级未设置课程表');
                                                                            }
                                                                        }
                                                                        this.setState({
                                                                            num: 0,
                                                                            active_class: item_.classid,
                                                                            tmp: Object.assign({}, self.state.tmp,
                                                                                {
                                                                                    [self.state.active_class]: self.state.result[self.state.active_class]
                                                                                }),
                                                                            open: true,
                                                                            list: self.state.schedules[item_.classid]
                                                                        })
                                                                    }}
                                                                    type="button">
                                                                    <i className="fa fa-window-restore"></i> 设置推送时间
                                                                </button>
                                                            </span>
                                                        </li>
                                                    })
                                                }
                                            </ul>
                                        </div>
                                        <Modal open={self.state.open}>
                                            <Modal.Header onclose={()=> {
                                                self.setState({open: false, selected: ''});
                                            }
                                            }>“{
                                                (self.state.list && self.state.list.classInfo) ?
                                                self.state.list && this.state.list.classInfo['class']['name'] : ''}”
                                                作业推送时间设置</Modal.Header>
                                            <Modal.Body >
                                                <Canlendar
                                                    multiSelect={false}
                                                    selected={(self.state.schedules && self.state.schedules[this.state.active_class]) ?
                                                        Object.assign({}, self.state.schedules[this.state.active_class].selected, self.state.schedules[this.state.active_class].tmp || {}) : {}}
                                                    classInfo={self.state.list}
                                                    onchange={(data)=> {
                                                        self.setState({
                                                            selected: data,
                                                            schedules: Object.assign({}, self.state.schedules,
                                                                {
                                                                    [this.state.active_class]: Object.assign({},
                                                                        self.state.schedules[this.state.active_class],
                                                                        {tmp: data})
                                                                }
                                                            ),

                                                        })
                                                        ;
                                                    }}>
                                                </Canlendar>
                                            </Modal.Body>
                                            <Modal.Footer
                                                onclose={()=> {
                                                    self.setState({open: false, selected: ''})
                                                }}
                                                onconfirm={()=> {
                                                    var res = (self.state.schedules[this.state.active_class].tmp &&
                                                    Object.keys(self.state.schedules[this.state.active_class].tmp)) ?
                                                        self.state.schedules[this.state.active_class].tmp :
                                                        self.state.schedules[this.state.active_class].selected;

                                                    item.onchange(index, Object.keys(res));
                                                    self.setState({
                                                        open: false,
                                                        selected: '',
                                                        schedules: Object.assign({}, self.state.schedules,
                                                            {
                                                                [this.state.active_class]: Object.assign({},
                                                                    self.state.schedules[this.state.active_class],
                                                                    {
                                                                        selected: res,
                                                                        tmp: {}
                                                                    })
                                                            }
                                                        ),
                                                    });
                                                }
                                                }/>
                                        </Modal>
                                    </FormItem>
                                } else {
                                    return <FormItem index={index} {...item} key={index}></FormItem>
                                }
                            })
                        }
                        <div className="form-group">
                            <label className="col-sm-2 control-label"></label>
                            <div className="col-sm-10"><span>说明：设置作业要推送的班级，并关联课程表时间，作业将在当天上课30分钟后可进行查看</span></div>
                        </div>
                        <FormGroup>
                            <Label></Label>
                            <InputGroup>
                                <button onClick={self.onsubmit} className="btn btn-success"
                                        type="submit">
                                    保存
                                </button>
                            </InputGroup>
                        </FormGroup>
                    </div>
                </Panel>
            </div>
        )
    }
});
function select(state) {
    return {
        user: state.user.user,
        // [md5Url.NEWS_CATEGORY]: state.fetchBySubject[md5Url.NEWS_CATEGORY],
        // [SUBJECT.NEWS_CATEGORY]: state.fetchBySubject[SUBJECT.NEWS_CATEGORY],
        [PAGE_SUBJECT.NEWS_ADD]: state.pageBySubject[PAGE_SUBJECT.NEWS_ADD]
    }
}
export default connect(select)(Component)